//
//  Recorder.m
//  CocoaRecorder
//
//  Created by Mathieu Tozer on 12/10/06.
//  Copyright 2006 __MyCompanyName__. All rights reserved.
//

#import "Recorder.h"
#import "AudioFileRecorder.mm"
#import "WordArrayController.h"
#import "DefinitionsArrayController.h"
#import "DefinitionMO.h"
#import "WordMO.h"
#import <QTKit/QTKit.h>

@implementation Recorder

-(IBAction)startStopPlaybackDefinition:(id)sender{
	NSLog(@"Starting new playback of definition");
	[self startDefinitionPlayback];
}

-(IBAction)startStopRecordingDefinition:(id)sender{
	if([[sender title] isEqualToString:@"Record"]){
		NSLog(@"Starting a new definition recording");
		currentDef = [[definitionArrryController selectedObjects] objectAtIndex:0]; //could probably use the sender as well.
		//set the filename for the recording
		NSString *defFileName = [[[[currentDef objectID] URIRepresentation] path] stringByStandardizingPath];
		NSString *actualFileName = [defFileName lastPathComponent]; // = xyz
		NSArray *paths = [defFileName pathComponents];
		NSString *entityName = [paths objectAtIndex:1];

		NSString *fullFolderPath = [[self location] stringByAppendingPathComponent:entityName];
		[[NSFileManager defaultManager] createDirectoryAtPath:[fullFolderPath stringByStandardizingPath] attributes:nil];
		currentDefFullPath = [[fullFolderPath stringByAppendingPathComponent:actualFileName] retain];
		actualFileName = [actualFileName stringByAppendingString:@".m4a"];
		[self setFileName:actualFileName];
		[self startRecording];	
		[sender setTitle:@"Stop"];
	}
	else if([[sender title] isEqualToString:@"Stop"]){
		NSLog(@"Stopping the recording of a definition");
		[self stopRecordingDefinition];
		[sender setTitle:@"Record"];
	}
	else return; // shouldn't really happen actually.
}

-(IBAction)deleteDefinitonRecording:(id)sender{
	DefinitionMO *def = [[definitionArrryController selectedObjects] objectAtIndex:0];
	NSLog(@"Removing recording for word: %@", [def valueForKey:@"word"]);
	[[NSFileManager defaultManager] removeFileAtPath:[NSHomeDirectory() stringByAppendingString:[def valueForKey:@"myRecording"]] handler:nil];	
	
	[def setValue:nil forKey:@"myRecording"];
	[recordStopRecordButton setTitle:@"Record!"];
	
}


-(IBAction)startStopPlayback:(id)sender{
		[self startPlayback];
}

-(IBAction)startStopRecording:(id)sender{
	if([[sender title] isEqualToString:@"Record!"]){
		NSLog(@"Starting a new recording");

		currentWord = [[wordArrayController selectedObjects] objectAtIndex:0]; //save this for after when recording is stopped
		//set the filename for the recording
		NSString *fName = [[[[currentWord objectID] URIRepresentation] path] stringByStandardizingPath]; 
	//	/word/xyz
		//create a new 'word' folder for all the recordings of words.
		NSString *actualFileName = [fName lastPathComponent]; // = xyz
		NSArray *paths = [fName pathComponents];
		NSString *entityName = [paths objectAtIndex:1];
		
		NSString *fullFolderPath = [[self location] stringByAppendingPathComponent:entityName];
		[[NSFileManager defaultManager] createDirectoryAtPath:[fullFolderPath stringByStandardizingPath] attributes:nil];
		currentWordFullPath = [[fullFolderPath stringByAppendingPathComponent:actualFileName] retain];
		actualFileName = [actualFileName stringByAppendingString:@".m4a"];
		[self setFileName:actualFileName];
		[self startRecording];	
		[sender setTitle:@"Stop"];
	}
	else {
		NSLog(@"Stopping recording");
		[self stopRecording];
		[sender setTitle:@"Record!"];
	}
}

-(void)stopRecordingDefinition{
	[self StopRecording];
	//collect our recording on the other side and encode it into core data
	NSString *fullPath = [self location];
	fullPath = [[fullPath stringByAppendingString:[self fileName]] stringByStandardizingPath];
	//move the file to it's correct location
	[[NSFileManager defaultManager] movePath:fullPath toPath:[currentDefFullPath stringByAppendingPathExtension:@"m4a"] handler:nil];
	
	//remove the homedirectory from the save location
	NSMutableArray *path = [currentDefFullPath pathComponents];
	[path removeObjectAtIndex:0]; // 
	[path removeObjectAtIndex:0]; // /users/
	[path removeObjectAtIndex:0]; // /mat/
	NSString *properPath = [NSString pathWithComponents:path];
	NSMutableString *includingBloodySlash = [NSMutableString stringWithString:@"/"];
	[includingBloodySlash appendString:properPath];
	
	
	[currentDef setValue:[includingBloodySlash stringByAppendingPathExtension:@"m4a"] forKey:@"myRecording"]; //now it's for keeps
	[currentDefFullPath release];
	
}

-(void)startRecording{
	[self StartRecording];
}

-(void)stopRecording{
	[self StopRecording];
	//collect our recording on the other side and encode it into core data
	NSString *fullPath = [self location];
	fullPath = [[fullPath stringByAppendingString:[self fileName]] stringByStandardizingPath];
	//move the file to it's correct location
	[[NSFileManager defaultManager] movePath:fullPath toPath:[currentWordFullPath stringByAppendingPathExtension:@"m4a"] handler:nil];
	
	//remove the homedirectory from the save location
	NSMutableArray *path = [currentWordFullPath pathComponents];
	[path removeObjectAtIndex:0]; // 
	[path removeObjectAtIndex:0]; // /users/
	[path removeObjectAtIndex:0]; // /mat/
	NSString *properPath = [NSString pathWithComponents:path];
	NSMutableString *includingBloodySlash = [NSMutableString stringWithString:@"/"];
	[includingBloodySlash appendString:properPath];
	
	
	[currentWord setValue:[[includingBloodySlash stringByAppendingPathExtension:@"m4a"] stringByStandardizingPath] forKey:@"myRecording"]; //now it's for keeps
	[currentWordFullPath release];
	
}

-(void)startDefinitionPlayback{
	DefinitionMO *def = [[definitionArrryController selectedObjects] objectAtIndex:0];
	NSLog(@"Starting Playback for def: %@", [def valueForKey:@"definition"]);
	NSString *fullPath = [def valueForKey:@"myRecording"];
	NSString *fullpathIncludingHomeDir = [NSHomeDirectory() stringByAppendingString:fullPath];
	NSSound *mySound = [[NSSound alloc] initWithContentsOfFile:fullpathIncludingHomeDir byReference:NO];
	[mySound play];
	[mySound release];
}

-(void)startPlayback{

	WordMO *word = [[wordArrayController selectedObjects] objectAtIndex:0];
	NSLog(@"Starting Playback for word: %@", [word valueForKey:@"word"]);
	NSString *fullPath = [word valueForKey:@"myRecording"];
	NSString *fullpathIncludingHomeDir = [NSHomeDirectory() stringByAppendingString:fullPath];
	NSSound *mySound = [[NSSound alloc] initWithContentsOfFile:fullpathIncludingHomeDir byReference:NO];
	[mySound play];
	[mySound release];
}

-(IBAction)deleteRecording:(id)sender{
	WordMO *word = [[wordArrayController selectedObjects] objectAtIndex:0];
	NSLog(@"Removing recording for word: %@", [word valueForKey:@"word"]);
	[[NSFileManager defaultManager] removeFileAtPath:[NSHomeDirectory() stringByAppendingString:[word valueForKey:@"myRecording"]] handler:nil];	
	
	[word setValue:nil forKey:@"myRecording"];
	[recordStopRecordButton setTitle:@"Record!"];
	
}

- (void) awakeFromNib{
	gIsRecording = false;
	gAudioFileRecorder = nil;
	gFileName = nil;
	
	// Basically you have to set 2 strings here
	// 1: location - the directory where the file will be stored
	// 2: fileName - the name of the file which will house your recording. Apple used m4a as the extension. Haven't tried anything else but.
	
	NSString *homeDir = NSHomeDirectory();
	NSString *applicationSupportFolder = [[[NSFileManager defaultManager] findSystemFolderType:kApplicationSupportFolderType 
																					 forDomain:kOnSystemDisk] stringByStandardizingPath];
	//create a temp assests folder if there isn't one available already
	NSString *tempAssetsFolder = [NSString stringWithFormat:@"%@%@/Words/Recordings/", homeDir, applicationSupportFolder];
	[[NSFileManager defaultManager] createDirectoryAtPath:[tempAssetsFolder stringByStandardizingPath] attributes:nil];
	
	
	/* * * * * * * * */
	[self setLocation:[NSString stringWithString:tempAssetsFolder]];
	[self setFileName:[NSString stringWithString:@"tempRecording.m4a"]];
	/* * * * * * * * */ 
	
	FSPathMakeRef ((UInt8 *)[[self location]  fileSystemRepresentation], &gParentDir, // here we convert our location string to a FSRef
				   NULL);
	//and here we convert our filename string to CFStringRef
	gFileName = CFStringCreateWithCString (kCFAllocatorDefault, [[self fileName] cString], kCFStringEncodingUTF8);
}

- (OSStatus)StartRecording{
	
	OSStatus err = noErr;
	
	if(gIsRecording)
		return noErr;
	
	if(gAudioFileRecorder)
		delete gAudioFileRecorder; gAudioFileRecorder = NULL; //delete the old audio recorder if we had one
		
		//and let's get a brand new one!
		gAudioFileRecorder = new DCAudioFileRecorder;	// here's where it's going.
		err = gAudioFileRecorder->Configure(gParentDir, gFileName, &gAACFormat);
		if(err != noErr)
		 {
			delete gAudioFileRecorder; gAudioFileRecorder = NULL;
			return err;
		 }
		
		err = gAudioFileRecorder->Start();
		if(err != noErr)
		 {
			delete gAudioFileRecorder; gAudioFileRecorder = NULL;
			return err;
		 }
		
		gIsRecording = true;
		return err;
}

- (OSStatus) StopRecording{
	OSStatus err = noErr;
	
	if(!gIsRecording)
		return noErr;
	
	err = gAudioFileRecorder->Stop(); //that's quite enough, thanks.
									  //err = SetControlTitleWithCFString(gRecordButtonView, CFSTR("Record"));
	
	// delete the object here so the async file I/O flushs
	delete gAudioFileRecorder; gAudioFileRecorder = NULL;
	gIsRecording = false;
	
	return err;
	
}

//accessors to the location and filename

- (NSString *)location {
    return [[location retain] autorelease];
}

- (void)setLocation:(NSString *)value {
    if (location != value) {
        [location release];
        location = [value copy];
	}
}

- (NSString *)fileName {
    return [[fileName retain] autorelease];
}

- (void)setFileName:(NSString *)value {
    if (fileName != value) {
        [fileName release];
        fileName = [value copy];
		//and here we convert our filename string to CFStringRef
		gFileName = CFStringCreateWithCString (kCFAllocatorDefault, [[self fileName] cString], kCFStringEncodingUTF8);
    }
}


@end
